#ifndef YHAIDA_CONDITION_H
#define YHAIDA_CONDITION_H
#include "../base/Utils.h"
#include "MutexLock.h"
#include <ctime>
#include <errno.h>
namespace yhaida
{
    class Condition : Utils::nocapyable
    {
    public:
        explicit Condition(MutexLock &m) : _mutex(m)
        {
            if (pthread_cond_init(&_cv, NULL))
            {
                printf("condition init go wrong!!");
            }
        }
        ~Condition()
        {
            pthread_cond_destroy(&_cv);
        }
        void wait()
        {
            pthread_cond_wait(&_cv, _mutex.getPthreadMutex());
        }
        //超时返回true,用在后续异步日志里面
        bool waitForSeconds(int seconds)
        {
            struct timespec abstime;
            clock_gettime(CLOCK_REALTIME, &abstime);
            abstime.tv_sec += seconds;
            return ETIMEDOUT == pthread_cond_timedwait(&_cv, _mutex.getPthreadMutex(), &abstime);
        }

        void notify()
        {
            pthread_cond_signal(&_cv);
        }
        void notifyAll()
        {
            pthread_cond_broadcast(&_cv);
        }

    private:
        MutexLock &_mutex;
        pthread_cond_t _cv;
    };
}

#endif